package middleware

import (
	"gitee.com/yangwencheng/vblog/apps/user"
	"gitee.com/yangwencheng/vblog/common"
	"gitee.com/yangwencheng/vblog/ioc"
	"gitee.com/yangwencheng/vblog/logger"
	"github.com/gin-gonic/gin"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {

		token := c.GetHeader("token")
		logger.GetLogger().Info().Any("token", token).Msg("token")
		srv := ioc.App().GetController(user.MODEL_NAME)
		userService := srv.(user.Service)

		in := user.NewValidateTokenRequest()
		in.AccessToken = token
		u, err := userService.ValidateToken(c, in)
		if err != nil {
			common.SendFail(c, err)
			c.Abort()
		} else {
			// 设置 example 变量
			c.Set("user_id", u.ID)
			c.Set("user_name", u.Username)
			c.Set("user", u)
			c.Next()
		}

	}
}
